package org.thanos.demo.config;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thanos.demo.consumer.MessageEventConsumer;
import org.thanos.demo.entity.MessageEvent;
import org.thanos.demo.entity.MessageEventFactory;
import org.thanos.demo.producer.MessageEventProducer;
import org.thanos.demo.vo.req.LocationMsg;

@Configuration
public class DisruptorConfig {

    @Bean(name = "disruptor")
    public Disruptor<MessageEvent<LocationMsg>> disruptor() {
        MessageEventFactory<LocationMsg> factory = new MessageEventFactory<>();
        int ringBufferSize = 1024;
        Disruptor<MessageEvent<LocationMsg>> disruptor = new Disruptor<>(factory, ringBufferSize, DaemonThreadFactory.INSTANCE);
        disruptor.handleEventsWith(messageEventConsumer());
        disruptor.start();
        return disruptor;
    }

    @Bean(name = "messageEventProducer")
    public MessageEventProducer<LocationMsg> messageEventProducer() {
        RingBuffer<MessageEvent<LocationMsg>> ringBuffer = disruptor().getRingBuffer();
        return new MessageEventProducer<>(ringBuffer);
    }

    @Bean(name = "messageEventConsumer")
    public MessageEventConsumer<LocationMsg> messageEventConsumer() {
        return new MessageEventConsumer<>();
    }
}
